package org.gcb.core.windows;

import java.util.Collection;
import java.util.logging.Logger;
import org.gcb.core.model.Toon;
import org.gcb.core.sandbox.ItemFromTransferHandler;
import org.gcb.core.ui.dnd.BackpackDropTargetListener;
import org.gcb.core.ui.nodes.EquipmentCarriedChildFactory;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.LookupListener;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.gcb.core.windows//Backpack//EN",
autostore = false)
public final class BackpackTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener{
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "BackpackTopComponent";
    private static ExplorerManager explorerManager = new ExplorerManager();
    private static BackpackTopComponent instance;
    private Lookup.Result<Toon> result = null;

    public BackpackTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(BackpackTopComponent.class, "CTL_BackpackTopComponent"));
        setToolTipText(NbBundle.getMessage(BackpackTopComponent.class, "HINT_BackpackTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
        associateLookup(ExplorerUtils.createLookup(explorerManager, getActionMap()));
//	iconView1.setDragSource(true);
//	iconView1.setDropTarget(true);
	iconView1.setTransferHandler(new ItemFromTransferHandler(null));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtCarriedWeight = new javax.swing.JTextField();
        txtNormalCarry = new javax.swing.JTextField();
        txtMaxCarry = new javax.swing.JTextField();
        txtMaxDrag = new javax.swing.JTextField();
        iconView1 = new org.openide.explorer.view.IconView();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.jPanel1.border.title"))); // NOI18N
        jPanel1.setLayout(new java.awt.GridLayout(2, 0));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.jLabel3.text")); // NOI18N
        jPanel1.add(jLabel3);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.jLabel4.text")); // NOI18N
        jPanel1.add(jLabel4);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.jLabel5.text")); // NOI18N
        jPanel1.add(jLabel5);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.jLabel6.text")); // NOI18N
        jPanel1.add(jLabel6);

        txtCarriedWeight.setEditable(false);
        txtCarriedWeight.setText(org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.txtCarriedWeight.text")); // NOI18N
        jPanel1.add(txtCarriedWeight);

        txtNormalCarry.setEditable(false);
        txtNormalCarry.setText(org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.txtNormalCarry.text")); // NOI18N
        jPanel1.add(txtNormalCarry);

        txtMaxCarry.setEditable(false);
        txtMaxCarry.setText(org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.txtMaxCarry.text")); // NOI18N
        jPanel1.add(txtMaxCarry);

        txtMaxDrag.setEditable(false);
        txtMaxDrag.setText(org.openide.util.NbBundle.getMessage(BackpackTopComponent.class, "BackpackTopComponent.txtMaxDrag.text")); // NOI18N
        jPanel1.add(txtMaxDrag);

        iconView1.setDragSource(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(iconView1, javax.swing.GroupLayout.DEFAULT_SIZE, 613, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(iconView1, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.openide.explorer.view.IconView iconView1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtCarriedWeight;
    private javax.swing.JTextField txtMaxCarry;
    private javax.swing.JTextField txtMaxDrag;
    private javax.swing.JTextField txtNormalCarry;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized BackpackTopComponent getDefault() {
        if (instance == null) {
            instance = new BackpackTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the BackpackTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized BackpackTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(BackpackTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof BackpackTopComponent) {
            return (BackpackTopComponent) win;
        }
        Logger.getLogger(BackpackTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        result = WindowManager.getDefault().findTopComponent("ToonListingTopComponent").getLookup().lookupResult(Toon.class);
        result.addLookupListener(this);
        resultChanged(new LookupEvent(result));
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return explorerManager;
    }

    @Override
    public void resultChanged(LookupEvent ev) {
        Lookup.Result r = (Result) ev.getSource();
        Collection<Toon> toons = r.allInstances();
        if (toons.isEmpty()) {
            return;
        }
        Toon t = toons.iterator().next();
	iconView1.setTransferHandler(new ItemFromTransferHandler(t));
	new BackpackDropTargetListener(iconView1, t);
//        iconView1.setDropTarget(new DropTarget(this, DnDConstants.ACTION_MOVE, new BackpackDropTargetListener(t), true));
        AbstractNode aNode = new AbstractNode(Children.create(new EquipmentCarriedChildFactory(t.getEquipment().getCarried()), true));
        explorerManager.setRootContext(aNode);
        txtCarriedWeight.setText(t.getEquipment().getCarried().getWeight()+"");
        txtNormalCarry.setText(t.getEquipment().getCarried().getNormalCarryWeight()+"");
        txtMaxCarry.setText(t.getEquipment().getCarried().getMaxCarryWeight()+"");
        txtMaxDrag.setText(t.getEquipment().getCarried().getMaxDragWeight()+"");
    }
}
